package com.ruoyi.yyq.controller;

import cn.hutool.extra.qrcode.QrCodeUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.alipay.easysdk.factory.Factory;
import com.alipay.easysdk.kernel.Config;
import com.alipay.easysdk.payment.common.models.AlipayTradeQueryResponse;
import com.alipay.easysdk.payment.facetoface.models.AlipayTradePrecreateResponse;
import com.ruoyi.yyq.domain.CarOrder;
import com.ruoyi.yyq.service.ICarOrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


@RestController
@RequestMapping("/alipay")
@CrossOrigin
public class AlipayController {

    @Autowired
    private ICarOrderService carOrderService;

    //获取订单的支付二维码的接口
    @GetMapping("/pay")
    public void pay(HttpServletResponse servletResponse, String outTradeNo)
            throws Exception {
        //支付宝接口配置
        Config config = new Config();
        //网关
        config.protocol = "https";
        config.gatewayHost = "openapi-sandbox.dl.alipaydev.com";
        //应用私钥钥
        config.merchantPrivateKey="MIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQCme0M+qKyhqqHFAMqAUEzXNmqONiHqFUsYMkiCC4dNMPKHR+Q/TGsneYoC2p3FbaoaGbqtIUlH56fWHWNCj9P3rU+22n4i3Uw/5n2z+syCOuAnAKQjzttE0pYA99sOC5HSXoGHmQrYgDgWMRrpkYVkwvr8PM8uviGnc0CAOSdBwUeNDZUPsBIOksHr90318w1tN4mISPwrPSFA0S61W5DDBw9/GGINLX/cTSlL6yoEDwZl/8MJxUk6yfhMJ79j/C2Nrl/4a5JQkB4s1azaE2qe+NKVLlL/ChvWob9q/OhyaZy2IjknwCI5mbtwyFkVXpxv/MPxyGc/TTrhyG01XqVrAgMBAAECggEAMwvyl4DixgNq7NwMO4Hjvc2aqJZimcMDrpykbPOZ/go3I1Hg46PL62Ox9KQR4lp44N3oxnNBZAHdDaMfL2aoiPYkTh36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K/qVE2B+x9P7UdFX1NUpCIpMgFVpwm7HBPJGCCJlqN9Z1LZRsfs7Xw==";
        // 支付宝公钥
        config.alipayPublicKey="MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAl4DRaQ1QFA1tA9T57/+PIcJnCXhOdhCHOHnuVuxxd7rQvBbmoz+yaXoIt2uTzaRMVKCPvjLDd+AqX4FSDDUe4uhaYTXqc/osC6HwDLP+HTZHsGfJaw0Fat3z9yDIUbprqnAtUOCNGix47lrVYeP/jjRJTJ4H55d5cWSyxLoT2YEuHva9rTwBR0lKH2/gU3g6fIUltqypuNVy3bkU8uE9gBmfU4LkBpecKUMbCyMeWdJg0hETf4oB/grRbG5uRf4RZsxwO1GxlWJbToI5duBk3ZQG4Tp/Ur4lGZwyDwVLLj1jIbwYW6FeUCafiSCCpe0VxpEiKQbnnR98ufMF2nla/QIDAQAB";
        //签名类型
        config.signType="RSA2";
        //appid
        config.appId="2021000148688015";
        //支付宝回调notifyUrl
        config.notifyUrl="http://localhost:8080/alipay/notify";
        //内网穿透
        config.notifyUrl=" http://dbe6b2ea.natappfree.cc/alipay/notify";
        Factory.setOptions(config);
        //发起调用支付宝接口
        AlipayTradePrecreateResponse response =
                Factory.Payment.FaceToFace().preCreate("ipone16 1t 256", outTradeNo, "1000");
        //响应解析
        String httpBody = response.getHttpBody();
        System.out.println("响应结果：");
        System.out.println(httpBody);
        //获取二维码信息
        JSONObject jsonObject = JSONUtil.parseObj(httpBody);
        String qrUrl = jsonObject.getJSONObject("alipay_trade_precreate_response").get("qr_code").toString();
        //生成二维码
        // 生成指定url对应的二维码到文件，宽和高都是300像素
        // QrCodeUtil.generate(qrUrl, 300, 300, FileUtil.file("d:/qrcode.jpg"));
        //设置响应servletResponse
        ServletOutputStream out = servletResponse.getOutputStream();
        QrCodeUtil.generate(qrUrl, 300, 300,"",out);
        out.close();
    }

    // 支付后回调函数
    @PostMapping("/notify")
    public  String  notifyUrl(HttpServletRequest request){
        System.out.println("回调。。。。。。");
//        获取支付结果
//        根据结果进行业务处理：修改订单的状态
        String outTradeNo = request.getParameter("out_trade_no");
        CarOrder carOrder = carOrderService.selectCarOrderById(Long.parseLong(outTradeNo));
        //当订单处于未支付状态时，修改订单状态为已支付
        if(carOrder.getStatus() == 0){
            carOrder.setStatus(1L);
        }
        carOrderService.updateCarOrder(carOrder);
        System.out.println("支付成功");
        System.out.println(carOrder);
        return  outTradeNo;
    }

    // 订单状态查询
    @GetMapping("/queryPay")
    public  String  queryPay(String outTradeNo) throws Exception {
        //支付宝接口配置
        Config config = new Config();
        //网关
        config.protocol = "https";
        config.gatewayHost = "openapi-sandbox.dl.alipaydev.com";
        //应用私钥钥
        config.merchantPrivateKey="";
        // 支付宝公钥
        config.alipayPublicKey="";
        //签名类型
        config.signType="RSA2";
        //appid
        config.appId="9021000124666928";
        Factory.setOptions(config);

//        查询支付结果
        AlipayTradeQueryResponse queryResponse = Factory.Payment.Common().query(outTradeNo);
        String httpBody = queryResponse.getHttpBody();
        System.out.println(httpBody);

        //解析支付结果
        JSONObject jsonObject = JSONUtil.parseObj(httpBody);
        String trade_status = jsonObject.getJSONObject("alipay_trade_query_response").get("trade_status").toString();

        return trade_status;
    }
}